﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.Common;

namespace BackendDeveloper_WS.Persistence
{
    class SqlDataManager 
    {
        /// <summary>
        /// Creates and returns a new sql connection.
        /// </summary>
        /// <returns>SqlConnection</returns>
        public SqlConnection createConnection() 
        {
            AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data"));
            SqlConnection myConnection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Orders_DataBase.mdf;Integrated Security=True");
            myConnection.Open();
            return myConnection;
        }

        /// <summary>
        /// This function creates a connection with the Sql Server DataBase, then executes the received SQL Server query and then closes the connection.
        /// </summary>
        /// <param name="query">query that will be executed</param>
        /// <param name="connection">Sql connection to the data base</param>
        /// <returns>DbDataReader object with the result of the execution of the query</returns>
        public SqlDataReader executeQuery(string query, SqlConnection connection) 
        {

            SqlDataReader myReader = null;
            SqlCommand myCommand = new SqlCommand(query, connection);
            myReader = myCommand.ExecuteReader();           
            return myReader;
        }

        /// <summary>
        /// Closes the sql connection
        /// </summary>
        /// <param name="connection">Sql connection to be closed</param>
        public void closeConnection(SqlConnection connection)
        {
            connection.Close();
        }
    }
}